package com.jungle.system.utils.chat;

import cn.hutool.Hutool;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.HttpMethod;
import com.jungle.common.exception.CharPostRequestException;
import com.jungle.system.domain.ChatCompletionRequest;
import com.jungle.system.domain.ChatMessage;
import com.jungle.system.domain.ExecuteRet;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.implementation.bytecode.Throw;
import okhttp3.*;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class OpenAiApi {
    @Value("${smart.open.ai.url}")
    private String url;
    @Value("${smart.open.ai.token}")
    private String token;

//    private static final MultiThreadedHttpConnectionManager CONNECTION_MANAGER= new MultiThreadedHttpConnectionManager();
//
//    static {
//        // 默认单个host最大链接数
//        CONNECTION_MANAGER.getParams().setDefaultMaxConnectionsPerHost(
//                Integer.valueOf(20));
//        // 最大总连接数，默认20
//        CONNECTION_MANAGER.getParams()
//                .setMaxTotalConnections(20);
//        // 连接超时时间
//        CONNECTION_MANAGER.getParams()
//                .setConnectionTimeout(60000);
//        // 读取超时时间
//        CONNECTION_MANAGER.getParams().setSoTimeout(60000);
//    }

    public ExecuteRet get(String path, Map<String, String> headers) {
        return null;
    }


//    public ExecuteRet post(String path, String json) {
//        try {
//            //创建GET请求
//            HttpGet httpGet = new HttpGet(url + path);
//            // 创建Httpclient对象
//            CloseableHttpClient httpClient = HttpClients.createDefault();
//            //发送请求
//            CloseableHttpResponse response = httpClient.execute(httpGet);
//            //判断响应状态
//            if (response.getStatusLine().getStatusCode() == 200) {
//                String result = EntityUtils.toString(response.getEntity(), "UTF-8"); //响应实体转String
//                log.info("Char Post请求");
//                return new ExecuteRet(true, result, HttpMethod.POST, 200);
//            } else {
//                throw new CharPostRequestException("Char Post请求异常:" + response.getStatusLine().getStatusCode());
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }

    /**
     * 获取所有可以用模型
     *
     * @param path 接口路径
     * @return
     */
    public ExecuteRet getAllModel(String path) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url + path)
                .addHeader("Authorization", "Bearer " + token)
                .build();
        try (Response response = client.newCall(request).execute()){
            ResponseBody resultBody = response.body();
            if (response.isSuccessful()) {
                log.info("Char 获取所有可以用模型");
            }else {
                throw new RuntimeException("获取OpenAI模型异常"+response.message());
            }
            return new ExecuteRet(true, resultBody.string(), null, 200);
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static final MediaType JSON = MediaType.get("application/json");

    /**
     * 调用CharGPT聊天接口
     *
     * @param path 接口路径
     * @param userDialog 用户对话内容
     * @return
     */
    public ExecuteRet post(String path, String userDialog) {
        ChatMessage chatMessage = new ChatMessage("user", userDialog);
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(chatMessage);
        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model("gpt-3.5-turbo")
                .messages(messages)
//                .user("user")
//                .max_tokens(500)
//                .temperature(1.0)
                .build();

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSONUtil.toJsonStr(chatCompletionRequest), JSON);
        Request request = new Request.Builder()
                .url(url + path)
                .addHeader("Authorization", "Bearer " + token)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            ResponseBody resultBody = response.body();
            String result = null;
            if (resultBody != null) {
                result = resultBody.string();
                log.info("Char Post请求");
            }
            return new ExecuteRet(true, result, null, 200);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
//
//    public ExecuteRet execute(HttpMethod method) {
//        HttpClient client = new HttpClient(CONNECTION_MANAGER);
//        int statusCode = -1;
//        String respStr = null;
//        boolean isSuccess = false;
//        try {
//            client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF8");
//            statusCode = client.executeMethod(method);
//            method.getRequestHeaders();
//
//            // log.info("执行结果statusCode = " + statusCode);
//            InputStreamReader inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
//            BufferedReader reader = new BufferedReader(inputStreamReader);
//            StringBuilder stringBuffer = new StringBuilder(100);
//            String str;
//            while ((str = reader.readLine()) != null) {
//                log.debug("逐行读取String = " + str);
//                stringBuffer.append(str.trim());
//            }
//            respStr = stringBuffer.toString();
//            if (respStr != null) {
//                log.info(String.format("执行结果String = %s, Length = %d", respStr, respStr.length()));
//            }
//            inputStreamReader.close();
//            reader.close();
//            // 返回200，接口调用成功
//            isSuccess = (statusCode == HttpStatus.SC_OK);
//        } catch (IOExceptionex) {
//
//        } finally {
//            method.releaseConnection();
//        }
//        return new ExecuteRet(isSuccess, respStr,method, statusCode);
//    }
}
